package com.buaa.student.service.impl;

import com.buaa.student.constant.DakaConstant;
import com.buaa.student.mapper.DakaTokenMapper;
import com.buaa.student.pojo.Dakatoken;
import com.buaa.student.service.DakaTokenService;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class DakaTokenServiceImpl implements DakaTokenService {

    @Autowired
    private DakaTokenMapper dakaTokenMapper;

    @Override
    public List<Dakatoken> getListByFlag(int flag) {
        List<Dakatoken> list = dakaTokenMapper.getSuccessOrFailList(flag);
        return list;
    }

    @Override
    public void autoDakaAll() {
        List<Dakatoken> all = dakaTokenMapper.getAll();
        autoDaka(all);
    }

    private void autoDaka(List<Dakatoken> dakatokenList){
        for (Dakatoken dakatoken : dakatokenList) {
            // TODO 1.在这里执行发请求去后台打卡的操作
            CloseableHttpClient httpClient = addCookieHttpClient(dakatoken.getEaiValue());
            try {
                //创建URLBuilder
                URIBuilder uriBuilder = new URIBuilder("https://app.buaa.edu.cn/buaaxsncov/wap/default/save");

                //2.创建HttpPost对象，设置URL地址
                URI uri = uriBuilder.build();
                HttpPost httpPost = new HttpPost(uri);

                httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36");

                //这个函数是用来添加打卡的参数的.加上请求体的参数之后的post请求
                HttpPost newHttpPost = addParameter(httpPost, dakatoken);

                //执行Post请求
                CloseableHttpResponse response = httpClient.execute(newHttpPost);

                //7.获取结果实体
                HttpEntity entity = response.getEntity();
                String body = "";
                if (entity != null) {
                    //按指定编码转换结果实体为String类型
                    body = EntityUtils.toString(entity);
                    System.out.println("post打卡请求的响应结果："+body);

                    int successStr = body.indexOf("操作成功");
                    if(successStr != -1){
                        // TODO 2.打卡后，要对打卡成功的名单的flag值设置为成功
                        dakaTokenMapper.updateById(dakatoken.getId(), DakaConstant.DakaStatusEnum.SUCCESS.getCode());
                    }else{
                        // TODO 2.打卡后，要对打卡失败的名单的flag值设置为失败
                        dakaTokenMapper.updateById(dakatoken.getId(), DakaConstant.DakaStatusEnum.FAIL.getCode());
                    }

                }
                //8.释放链接
                response.close();


            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }


    /**
     * 返回包含必备的Cookie值的HttpClient
     *
     * @param eaiValue 已登录状态的凭证
     * @return
     */
    private CloseableHttpClient addCookieHttpClient(String eaiValue) {

        BasicCookieStore cookieStore = new BasicCookieStore();

        //设置eai-sess
        BasicClientCookie cookieEai = new BasicClientCookie("eai-sess", eaiValue);
        cookieEai.setVersion(0);
        cookieEai.setDomain("app.buaa.edu.cn");
        cookieEai.setPath("/");
        cookieStore.addCookie(cookieEai);

        //设置UUkey
        BasicClientCookie cookieUUkey = new BasicClientCookie("UUkey", "6d9f8a1dd6e0322c86e22b8ab6a8df3c");
        cookieUUkey.setVersion(0);
        cookieUUkey.setDomain("app.buaa.edu.cn");
        cookieUUkey.setPath("/");
        cookieStore.addCookie(cookieUUkey);

        //设置xxbh21.8
        BasicClientCookie cookieXxbh = new BasicClientCookie("xxbh21.8", "94424103");
        cookieXxbh.setVersion(0);
        cookieXxbh.setDomain("app.buaa.edu.cn");
        cookieXxbh.setPath("/");
        cookieStore.addCookie(cookieXxbh);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        return httpClientBuilder.setDefaultCookieStore(cookieStore).build();
    }


    private HttpPost addParameter(HttpPost httpPost, Dakatoken dakatoken){

        List<NameValuePair> parameters = new ArrayList<>();

        /**
         * 1班周安吉不是按照默认的来打卡，所以他的字段和默认的不太一样.SY1906105
         * sfzs: 0
         * bzxyy: 4
         */





        if("SY1906105".equals(dakatoken.getStuNum()) || "SY1906113".equals(dakatoken.getStuNum())){
            //这是周安吉的，也是胡俊涛的
            //sfzs=0
            parameters.add(new BasicNameValuePair("sfzs","0"));
            //&bzxyy=4
            parameters.add(new BasicNameValuePair("bzxyy","4"));
        }else{
            //这是默认的，
            //sfzs=1
            parameters.add(new BasicNameValuePair("sfzs","1"));
            //&bzxyy=
            parameters.add(new BasicNameValuePair("bzxyy",""));
        }

        //&bzxyy_other=
        parameters.add(new BasicNameValuePair("bzxyy_other",""));
        //&brsfzc=1
        parameters.add(new BasicNameValuePair("brsfzc","1"));
        //&tw=
        parameters.add(new BasicNameValuePair("tw",""));
        //&sfcxzz=
        parameters.add(new BasicNameValuePair("sfcxzz",""));
        //&zdjg=
        parameters.add(new BasicNameValuePair("zdjg",""));
        //&zdjg_other=
        parameters.add(new BasicNameValuePair("zdjg_other",""));
        //&sfgl=
        parameters.add(new BasicNameValuePair("sfgl",""));
        //&gldd=
        parameters.add(new BasicNameValuePair("gldd",""));
        //&gldd_other=
        parameters.add(new BasicNameValuePair("gldd_other",""));
        //&glyy=
        parameters.add(new BasicNameValuePair("glyy",""));
        //&glyy_other=
        parameters.add(new BasicNameValuePair("glyy_other",""));
        //&gl_start=
        parameters.add(new BasicNameValuePair("gl_start",""));
        //&gl_end=
        parameters.add(new BasicNameValuePair("gl_end",""));
        //&sfmqjc=
        parameters.add(new BasicNameValuePair("sfmqjc",""));
        //&sfzc_14=1
        parameters.add(new BasicNameValuePair("sfzc_14","1"));
        //&sfqw_14=0
        parameters.add(new BasicNameValuePair("sfqw_14","0"));
        //&sfqw_14_remark=
        parameters.add(new BasicNameValuePair("sfqw_14_remark",""));
        //&sfzgfx=0
        parameters.add(new BasicNameValuePair("sfzgfx","0"));
        //&sfzgfx_remark=
        parameters.add(new BasicNameValuePair("sfzgfx_remark",""));
        //&sfjc_14=0
        parameters.add(new BasicNameValuePair("sfjc_14","0"));
        //&sfjc_14_remark=
        parameters.add(new BasicNameValuePair("sfjc_14_remark",""));
        //&sfjcqz_14=0
        parameters.add(new BasicNameValuePair("sfjcqz_14","0"));
        //&sfjcqz_14_remark=
        parameters.add(new BasicNameValuePair("sfjcqz_14_remark",""));
        //&sfgtjz_14=0
        parameters.add(new BasicNameValuePair("sfgtjz_14","0"));
        //&sfgtjz_14_remark=
        parameters.add(new BasicNameValuePair("sfgtjz_14_remark",""));
        //&szsqqz=0
        parameters.add(new BasicNameValuePair("szsqqz","0"));
        //&sfyqk=
        parameters.add(new BasicNameValuePair("sfyqk",""));
        //&szdd=1
        parameters.add(new BasicNameValuePair("szdd","1"));

        if("SY1906113".equals(dakatoken.getStuNum())){
            parameters.add(new BasicNameValuePair("area","浙江省 杭州市 西湖区"));
            parameters.add(new BasicNameValuePair("city","杭州市"));
            parameters.add(new BasicNameValuePair("province","浙江省"));
            parameters.add(new BasicNameValuePair("address","浙江省杭州市西湖区西湖街道杭州西湖风景名胜区曲院风荷"));
            parameters.add(new BasicNameValuePair("geo_api_info","{\"type\":\"complete\",\"info\":\"SUCCESS\",\"status\":1,\"cEa\":\"jsonp_945411_\",\"position\":{\"Q\":30.24946,\"R\":120.13414,\"lng\":120.13414,\"lat\":30.24946},\"message\":\"Get ipLocation success.Get address success.\",\"location_type\":\"ip\",\"accuracy\":null,\"isConverted\":true,\"addressComponent\":{\"citycode\":\"0571\",\"adcode\":\"330106\",\"businessAreas\":[{\"name\":\"西湖\",\"id\":\"330106\",\"location\":{\"Q\":30.253167,\"R\":120.137878,\"lng\":120.137878,\"lat\":30.253167}},{\"name\":\"北山\",\"id\":\"330106\",\"location\":{\"Q\":30.263047,\"R\":120.14288099999999,\"lng\":120.142881,\"lat\":30.263047}},{\"name\":\"龙井\",\"id\":\"330106\",\"location\":{\"Q\":30.22844,\"R\":120.11954800000001,\"lng\":120.119548,\"lat\":30.22844}}],\"neighborhoodType\":\"风景名胜;风景名胜;国家级景点\",\"neighborhood\":\"杭州西湖风景名胜区\",\"building\":\"\",\"buildingType\":\"\",\"street\":\"北山街\",\"streetNumber\":\"79-1号\",\"country\":\"中国\",\"province\":\"浙江省\",\"city\":\"杭州市\",\"district\":\"西湖区\",\"township\":\"西湖街道\"},\"formattedAddress\":\"浙江省杭州市西湖区西湖街道杭州西湖风景名胜区曲院风荷\",\"roads\":[],\"crosses\":[],\"pois\":[]}"));
        }else{
            //&area=%E5%8C%97%E4%BA%AC%E5%B8%82%20%E5%8C%97%E4%BA%AC%E5%B8%82%20%E6%B5%B7%E6%B7%80%E5%8C%BA
            parameters.add(new BasicNameValuePair("area","北京市 海淀区"));
            //&city=%E5%8C%97%E4%BA%AC%E5%B8%82
            parameters.add(new BasicNameValuePair("city","北京市"));
            //&province=%E5%8C%97%E4%BA%AC%E5%B8%82
            parameters.add(new BasicNameValuePair("province","北京市"));
            //&address=%E5%8C%97%E4%BA%AC%E5%B8%82%E6%B5%B7%E6%B7%80%E5%8C%BA%E8%8A%B1%E5%9B%AD%E8%B7%AF%E8%A1%97%E9%81%93%E5%8C%97%E4%BA%AC%E8%88%AA%E7%A9%BA%E8%88%AA%E5%A4%A9%E5%A4%A7%E5%AD%A6%E5%8C%97%E4%BA%AC%E8%88%AA%E7%A9%BA%E8%88%AA%E5%A4%A9%E5%A4%A7%E5%AD%A6%E5%AD%A6%E9%99%A2%E8%B7%AF%E6%A0%A1%E5%8C%BA
            parameters.add(new BasicNameValuePair("address","北京市海淀区花园路街道北京航空航天大学新主楼G座北京航空航天大学学院路校区"));
            //&geo_api_info=%7B%22type%22%3A%22complete%22%2C%22position%22%3A%7B%22Q%22%3A39.980918240018%2C%22R%22%3A116.35088840060803%2C%22lng%22%3A116.350888%2C%22lat%22%3A39.980918%7D%2C%22location_type%22%3A%22html5%22%2C%22message%22%3A%22Get%20geolocation%20success.Convert%20Success.Get%20address%20success.%22%2C%22accuracy%22%3A29%2C%22isConverted%22%3Atrue%2C%22status%22%3A1%2C%22addressComponent%22%3A%7B%22citycode%22%3A%22010%22%2C%22adcode%22%3A%22110108%22%2C%22businessAreas%22%3A%5B%7B%22name%22%3A%22%E4%BA%94%E9%81%93%E5%8F%A3%22%2C%22id%22%3A%22110108%22%2C%22location%22%3A%7B%22Q%22%3A39.99118%2C%22R%22%3A116.34157800000003%2C%22lng%22%3A116.341578%2C%22lat%22%3A39.99118%7D%7D%2C%7B%22name%22%3A%22%E7%89%A1%E4%B8%B9%E5%9B%AD%22%2C%22id%22%3A%22110108%22%2C%22location%22%3A%7B%22Q%22%3A39.977965%2C%22R%22%3A116.37172700000002%2C%22lng%22%3A116.371727%2C%22lat%22%3A39.977965%7D%7D%5D%2C%22neighborhoodType%22%3A%22%E7%94%9F%E6%B4%BB%E6%9C%8D%E5%8A%A1%3B%E7%94%9F%E6%B4%BB%E6%9C%8D%E5%8A%A1%E5%9C%BA%E6%89%80%3B%E7%94%9F%E6%B4%BB%E6%9C%8D%E5%8A%A1%E5%9C%BA%E6%89%80%22%2C%22neighborhood%22%3A%22%E5%8C%97%E4%BA%AC%E8%88%AA%E7%A9%BA%E8%88%AA%E5%A4%A9%E5%A4%A7%E5%AD%A6%22%2C%22building%22%3A%22%22%2C%22buildingType%22%3A%22%22%2C%22street%22%3A%22%E5%AD%A6%E9%99%A2%E8%B7%AF%22%2C%22streetNumber%22%3A%2237%E5%8F%B7%22%2C%22country%22%3A%22%E4%B8%AD%E5%9B%BD%22%2C%22province%22%3A%22%E5%8C%97%E4%BA%AC%E5%B8%82%22%2C%22city%22%3A%22%22%2C%22district%22%3A%22%E6%B5%B7%E6%B7%80%E5%8C%BA%22%2C%22township%22%3A%22%E8%8A%B1%E5%9B%AD%E8%B7%AF%E8%A1%97%E9%81%93%22%7D%2C%22formattedAddress%22%3A%22%E5%8C%97%E4%BA%AC%E5%B8%82%E6%B5%B7%E6%B7%80%E5%8C%BA%E8%8A%B1%E5%9B%AD%E8%B7%AF%E8%A1%97%E9%81%93%E5%8C%97%E4%BA%AC%E8%88%AA%E7%A9%BA%E8%88%AA%E5%A4%A9%E5%A4%A7%E5%AD%A6%E5%8C%97%E4%BA%AC%E8%88%AA%E7%A9%BA%E8%88%AA%E5%A4%A9%E5%A4%A7%E5%AD%A6%E5%AD%A6%E9%99%A2%E8%B7%AF%E6%A0%A1%E5%8C%BA%22%2C%22roads%22%3A%5B%5D%2C%22crosses%22%3A%5B%5D%2C%22pois%22%3A%5B%5D%2C%22info%22%3A%22SUCCESS%22%7D
            parameters.add(new BasicNameValuePair("geo_api_info","{\"type\":\"complete\",\"info\":\"SUCCESS\",\"status\":1,\"cEa\":\"jsonp_661432_\",\"position\":{\"Q\":39.98101,\"R\":116.35108000000002,\"lng\":116.35108,\"lat\":39.98101},\"message\":\"Get ipLocation success.Get address success.\",\"location_type\":\"ip\",\"accuracy\":null,\"isConverted\":true,\"addressComponent\":{\"citycode\":\"010\",\"adcode\":\"110108\",\"businessAreas\":[{\"name\":\"五道口\",\"id\":\"110108\",\"location\":{\"Q\":39.99118,\"R\":116.34157800000003,\"lng\":116.341578,\"lat\":39.99118}},{\"name\":\"牡丹园\",\"id\":\"110108\",\"location\":{\"Q\":39.977965,\"R\":116.37172700000002,\"lng\":116.371727,\"lat\":39.977965}}],\"neighborhoodType\":\"生活服务;生活服务场所;生活服务场所\",\"neighborhood\":\"北京航空航天大学\",\"building\":\"北京航空航天大学新主楼G座\",\"buildingType\":\"科教文化服务;学校;高等院校\",\"street\":\"学院路\",\"streetNumber\":\"37号\",\"country\":\"中国\",\"province\":\"北京市\",\"city\":\"\",\"district\":\"海淀区\",\"township\":\"花园路街道\"},\"formattedAddress\":\"北京市海淀区花园路街道北京航空航天大学新主楼G座北京航空航天大学学院路校区\",\"roads\":[],\"crosses\":[],\"pois\":[]}"));
        }
        //&gwdz=
        parameters.add(new BasicNameValuePair("gwdz",""));
        //&is_move=0
        parameters.add(new BasicNameValuePair("is_move","0"));
        //&move_reason=
        parameters.add(new BasicNameValuePair("move_reason",""));
        //&move_remark=
        parameters.add(new BasicNameValuePair("move_remark",""));
        // TODO 0.注意这里是名字  “王康明”的urlencode为 “%E7%8E%8B%E5%BA%B7%E6%98%8E”
        //&realname=%E6%88%B4%E4%B8%B9%E9%9D%92
//        String nameEncode = "";
//        try {
//            nameEncode = URLEncoder.encode(dakatoken.getStuName(), "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        parameters.add(new BasicNameValuePair("realname",dakatoken.getStuName()));


        //&number=ZY1906809
        //TODO 1.注意，这里是填学号
        parameters.add(new BasicNameValuePair("number",dakatoken.getStuNum()));
        //&uid=376649  TODO 这里的这个uid可能有坑
        parameters.add(new BasicNameValuePair("uid","376649"));
        //&created=1620901044
        //TODO 2.注意，这里是前一天的时间戳
        parameters.add(new BasicNameValuePair("created", Long.toString(System.currentTimeMillis()-86400*1000L)));
        //&date=20210513
        //TODO 3.注意，这里是前一天的日期
        String dateStr = new Date(System.currentTimeMillis() - 86400*1000L).toString().replace("-", "");
        parameters.add(new BasicNameValuePair("date", dateStr));
        //&id=2512472 TODO 这里的这个id可能有坑
        parameters.add(new BasicNameValuePair("id","2512472"));
        //&gwszdd=
        parameters.add(new BasicNameValuePair("gwszdd",""));
        //&created_uid=300068
        parameters.add(new BasicNameValuePair("created_uid","300068"));

        UrlEncodedFormEntity formEntity = null;

        try {
            formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httpPost.setEntity(formEntity);

        return httpPost;
    }

    @Override
    public void autoDakaFail() {
        // TODO 3.只对打卡失败的进行重试打卡
        List<Dakatoken> failList = dakaTokenMapper.getSuccessOrFailList(DakaConstant.DakaStatusEnum.FAIL.getCode());
        autoDaka(failList);
    }

    @Override
    public void resetAll() {
        List<Dakatoken> all = dakaTokenMapper.getAll();
        for (Dakatoken dakatoken : all) {
            // 每天都重置为打卡失败的状态
            dakaTokenMapper.updateById(dakatoken.getId(), DakaConstant.DakaStatusEnum.FAIL.getCode());
        }
    }
}
